package com.ply.flashsalessystem.schedule;

import com.ply.flashsalessystem.entity.pojo.Goods;
import com.ply.flashsalessystem.entity.pojo.OrderTime;
import com.ply.flashsalessystem.exception.GoodsException;
import com.ply.flashsalessystem.mapper.OrderTimeMapper;
import com.ply.flashsalessystem.service.GoodsService;
import com.ply.flashsalessystem.service.OrderTimeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ScheduledForDynamicCron implements SchedulingConfigurer {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderTimeService orderTimeService;

    @Autowired
    OrderTimeMapper orderTimeMapper;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    private static final String DEFAULT_CRON = "0 0 20 * * ?";
    private String cron = DEFAULT_CRON;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            // 定时任务的业务逻辑
            System.out.println("动态修改定时任务cron参数，当前时间：" + dateFormat.format(new Date()));
            log.debug("执行 更新 商品数量 恢复 默认值");
            updateGoodNums();
        }, (triggerContext) -> {
            // 定时任务触发，可修改定时任务的执行周期
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecDate = trigger.nextExecutionTime(triggerContext);
            return nextExecDate;
        });
    }

    public void setCron(String cron) {
        OrderTime byId = orderTimeService.query(1);
        // 每天的 定时 时间
        LocalTime time = byId.getTime();
        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();
        String cronText = second + " " + minute + " " + hour +  "* * ?";

        System.out.println("当前cron="+this.cron+"->将被改变为："+cronText);
        this.cron = cronText;
    }


    //每天 定时 修改 good 库存量
    public void updateGoodNums(){
        List<Goods> list = goodsService.list();
        for (Goods goods : list) {
            double defaultRemain = goods.getDefaultRemain();
            goods.setRemainNums(defaultRemain);
            if (!goodsService.updateById(goods)) {
                throw new GoodsException("每天 定时 更新 商品 库存量失败");
            }
        }
    }
}